package Test;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class DownloadFilePool {
	/*
		防止低概率事件，也就是所谓CPU质量的乱序执行 volatile
	 */
	private static volatile DownloadFilePool INSTANCE;
	// 网络资源路径
	private String urlLocation;
	// 存储路径
	private String filePath;
	// 多少个线程
	private int poolLength;
	//设置下载名称
	private String fileName;

	CountDownLatch countDownLatch = new CountDownLatch(poolLength);


	public String getFilePath() {
		return filePath;
	}

	public String getUrlLocation() {
		return urlLocation;
	}

	public void setUrlLocation(String urlLocation) {
		this.urlLocation = urlLocation;
	}

	public String getFileName() {
		return fileName;
	}

	public void setFileName(String fileName) {
		this.fileName = fileName;
	}

	private DownloadFilePool(String urlLocation,String fileName,Integer poolLength,String filePath) {
		super();
        // 如果 保存路径为空则默认存在 D盘，文件名跟下载名相同
		if (filePath == null) {
			//String fileName = urlLocation.substring(urlLocation.lastIndexOf("/") + 1);
			filePath = "/Users/zhubo/picture/" + fileName+ ".png";
		}

		this.urlLocation = urlLocation;
		this.filePath = filePath;
		this.poolLength = poolLength;
	}

	/**
	 * 初始化对象加锁，并且使得 DownloadFilePool 是线程可见性的
	 * @return
	 */
	public static DownloadFilePool getInstance(String urlLocation,String fileName,Integer poolLength,String filePath){
			synchronized (DownloadFilePool.class){
					INSTANCE = new DownloadFilePool(urlLocation,fileName,poolLength,filePath);
			}

		return INSTANCE;
	}

	/**
	 * 下载文件具体方法
	 */
	public void getFile() {
		try {
			// 获取文件长度
			long fileLength = Util.getHttpConnection(urlLocation).getContentLengthLong();
			Util.sum = fileLength;

			ExecutorService pool = Executors.newCachedThreadPool();
			// 获取每片大小
			long slice = fileLength / poolLength;
			for (int i = 0; i < poolLength; i++) {
				long start = i * slice;
				long end = (i + 1) * slice - 1;

				if (i == poolLength - 1) {
					start = i * slice;
					end = fileLength;
				}
				System.out.println(start + "----->" + end);

// 创建下载类
				DownloadFileRang downloadFileRang = new DownloadFileRang(start, end, urlLocation, filePath);
// 执行线程
				pool.execute(downloadFileRang);
			}
// 关闭线程池
			pool.shutdown();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
